package com.common.app.utls

import android.app.Activity
import android.graphics.Bitmap
import android.graphics.Color
import com.common.app.data.api.ApiConstant
import com.common.app.scan.ScanQrCodeActivity
import com.google.zxing.BarcodeFormat
import com.google.zxing.EncodeHintType
import com.google.zxing.MultiFormatWriter
import com.google.zxing.WriterException
import com.google.zxing.common.BitMatrix
import com.google.zxing.integration.android.IntentIntegrator
import com.google.zxing.qrcode.QRCodeWriter
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel
import com.journeyapps.barcodescanner.BarcodeEncoder
import java.util.*

object QRCodeHelper {

    /**
     * 打开二维码扫描
     * constant : 返回的code
     */
    fun startZxing(activity: Activity?, requestCode: Int){
        //二维码扫描
        IntentIntegrator(activity)
                .setDesiredBarcodeFormats(IntentIntegrator.ALL_CODE_TYPES)// 扫码的类型,可选：一维码，二维码，一/二维码
                //.setPrompt("请对准二维码")// 设置提示语
                .setCameraId(0)// 选择摄像头,可使用前置或者后置
                .setBeepEnabled(true)// 是否开启声音,扫完码之后会"哔"的一声
                .setCaptureActivity(ScanQrCodeActivity::class.java)//自定义扫码界面
                .setRequestCode(requestCode)
                .initiateScan()// 初始化扫码
    }

    /**
     * 生成二维码
     */
    fun encodeAsBitmap(str: String): Bitmap? {
        var bitmap: Bitmap? = null
        var result: BitMatrix? = null
        val multiFormatWriter = MultiFormatWriter()
        try {
            result = multiFormatWriter.encode(str, BarcodeFormat.QR_CODE, 200, 200)
            // 使用 ZXing Android Embedded 要写的代码
            val barcodeEncoder = BarcodeEncoder()
            bitmap = barcodeEncoder.createBitmap(result!!)
        } catch (e: WriterException) {
            e.printStackTrace()
        } catch (iae: IllegalArgumentException) { // ?
            return null
        }

        // 如果不使用 ZXing Android Embedded 的话，要写的代码

        //        int w = result.getWidth();
        //        int h = result.getHeight();
        //        int[] pixels = new int[w * h];
        //        for (int y = 0; y < h; y++) {
        //            int offset = y * w;
        //            for (int x = 0; x < w; x++) {
        //                pixels[offset + x] = result.get(x, y) ? BLACK : WHITE;
        //            }
        //        }
        //        bitmap = Bitmap.createBitmap(w,h,Bitmap.Config.ARGB_8888);
        //        bitmap.setPixels(pixels,0,100,0,0,w,h);

        return bitmap
    }

    /**
     * 判断是否是官方二维码
     * lytd_login?token=abcd
     */
    fun isOfficialQrCode(text: String): Boolean {
        return text.isNullOrEmpty().not() && (text.startsWith("sosou") || text.contains(ApiConstant.getBaseUrl()))
    }

    /**
     * 删除白边
     */
    private fun deleteWhite(matrix: BitMatrix): BitMatrix? {
        val rec = matrix.enclosingRectangle
        val resWidth = rec[2] + 1
        val resHeight = rec[3] + 1
        val resMatrix = BitMatrix(resWidth, resHeight)
        resMatrix.clear()
        for (i in 0 until resWidth) {
            for (j in 0 until resHeight) {
                if (matrix[i + rec[0], j + rec[1]]) resMatrix[i] = j
            }
        }
        return resMatrix
    }

    fun Create2DCode(str: String?, width: Int, height: Int): Bitmap? {
        var width = width
        var height = height
        return try {
            val hints = Hashtable<EncodeHintType, Any>()
            hints[EncodeHintType.CHARACTER_SET] = "utf-8"
            hints[EncodeHintType.ERROR_CORRECTION] = ErrorCorrectionLevel.H
            hints[EncodeHintType.MARGIN] = 1
            var matrix = QRCodeWriter().encode(str, BarcodeFormat.QR_CODE, width, height)
            matrix = deleteWhite(matrix) //删除白边
            width = matrix.width
            height = matrix.height
            val pixels = IntArray(width * height)
            for (y in 0 until height) {
                for (x in 0 until width) {
                    if (matrix[x, y]) {
                        pixels[y * width + x] = Color.BLACK
                    } else {
                        pixels[y * width + x] = Color.WHITE
                    }
                }
            }
            val bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888)
            bitmap.setPixels(pixels, 0, width, 0, 0, width, height)
            bitmap
        } catch (e: Exception) {
            null
        }
    }

}